package com.guagua.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guagua.common.exception.BusinessException;
import com.guagua.system.dto.PasswordUpdateDTO;
import com.guagua.system.dto.UserUpdateDTO;
import com.guagua.system.entity.User;
import com.guagua.system.mapper.UserMapper;
import com.guagua.system.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Override
    public User getUserByUsername(String username) {
        // 先尝试用户名查询
        User user = userMapper.selectOne(
            new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
        );
        
        // 如果找不到，尝试用邮箱查询
        if (user == null) {
            user = userMapper.selectOne(
                new LambdaQueryWrapper<User>()
                    .eq(User::getEmail, username)
            );
        }
        
        return user;
    }
    
    @Override
    public boolean isUsernameExists(String username) {
        return lambdaQuery().eq(User::getUsername, username).exists();
    }
    
    @Override
    public boolean isEmailExists(String email) {
        return lambdaQuery().eq(User::getEmail, email).exists();
    }

    @Override
    public void updateUserInfo(Long userId, UserUpdateDTO dto) {
        // 检查邮箱是否被其他用户使用
        boolean emailExists = lambdaQuery()
            .eq(User::getEmail, dto.getEmail())
            .ne(User::getId, userId)
            .exists();
            
        if (emailExists) {
            throw new BusinessException("邮箱已被使用");
        }
        
        // 更新用户信息
        User user = new User();
        user.setId(userId);
        user.setNickname(dto.getNickname());
        user.setEmail(dto.getEmail());
        user.setAvatar(dto.getAvatar());
        
        updateById(user);
    }

    @Override
    public void updatePassword(Long userId, PasswordUpdateDTO dto) {
        User user = getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 验证原密码
        if (!passwordEncoder.matches(dto.getOldPassword(), user.getPassword())) {
            throw new BusinessException("原密码错误");
        }
        
        // 更新密码
        user.setPassword(passwordEncoder.encode(dto.getNewPassword()));
        updateById(user);
    }

} 